package com.hnust.root.web.config;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

/**
 * @Author zhusir
 * @Date 2019/1/31
 * @Desc 异步任务配置
 */
@Configuration
@EnableAsync
public class AsynConfig implements AsyncConfigurer {

    private static final Log LOGGER = LogFactory.get();

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(100);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60 * 10);
        executor.setThreadNamePrefix("AsyncThread-");
        executor.initialize(); //如果不初始化，导致找到不到执行器
        return executor;
    }

    /**
     * 捕获异步任务抛出的异常
     * @return
     */
    @Override
     public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
                 return new SpringAsyncExceptionHandler();
    }
    class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
            LOGGER.error("异步任务发生错误，error method : {}, error  msg: {}", method.getName(), throwable.getMessage());
        }
    }
}
